import {
  deleteUserUsingPost,
  listUserVoByPageUsingPost,
  updateUserUsingPost,
} from '@/services/zengjin/userController';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { message } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
export const waitTimePromise = async (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};
const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};
type GithubIssueItem = {
  id: number;
  userName?: string;
  userAvatar?: string;
  userAccount?: string;
  userRole?: string;
  createTime?: string;
};
const UserList: React.FC = () => {
  const columns: ProColumns<GithubIssueItem>[] = [
    {
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '头像',
      valueType: 'avatar',
      dataIndex: 'userAvatar',
      search: false,
      editable: false,
      width: 60,
    },
    {
      title: '昵称',
      dataIndex: 'userName',
      copyable: true,
      search: false,
      ellipsis: true,
      editable: false,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: '账户',
      dataIndex: 'userAccount',
      copyable: true,
      ellipsis: true,
      search: false,
      editable: false,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: '权限',
      dataIndex: 'userRole',
      ellipsis: true,
      search: false,
      valueEnum: {
        user: {
          text: '普通用户',
          status: 'Default',
        },
        admin: {
          text: '管理员',
          status: 'Processing',
        },
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: '创建时间',
      key: 'createTime',
      dataIndex: 'createTime',
      valueType: 'date',
      sorter: true,
      editable: false,
      hideInSearch: true,
    },

    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            deleteUser(record.id);
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  const actionRef = useRef<ActionType>();
  const initSearchParams = {
    current: 1,
    pageSize: 5,
  };

  const [searchParams, setSearchParams] = useState<API.UserQueryRequest>({ ...initSearchParams });
  const [usertList, setUsertList] = useState<API.UserVO[]>();
  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);
  /**
   * 获取数据
   */
  const getDate = async () => {
    setLoading(true);
    try {
      const res = await listUserVoByPageUsingPost(searchParams);
      if (res.data) {
        setUsertList(res.data.records ?? []);
        setTotal(res.data.total ?? 0);
      } else {
        message.error('获取用户失败');
      }
    } catch (e: any) {
      message.error('获取用户失败' + e.message);
    }
    setLoading(false);
  };
  /**
   * 编辑用户权限
   */
  const editUser = async (id: number, userRole: string | undefined) => {
    setLoading(true);
    const param = {
      id: id,
      userRole: userRole,
    };
    try {
      const res = await updateUserUsingPost(param);
      if (res.code == 0) {
        message.success('保存成功');
        getDate();
      } else {
        message.error('编辑失败' + res.message);
      }
    } catch (e: any) {
      message.error('保存失败' + e.message);
    }

    setLoading(false);
  };
  /**
   * 删除用户
   */
  const deleteUser = async (deleteParam: number) => {
    console.log('删除了' + deleteParam);
    setLoading(true);
    const deleteRequest: API.DeleteRequest = { id: deleteParam };
    try {
      const res = await deleteUserUsingPost(deleteRequest);
      if (res.code == 0) {
        message.success('删除成功');
        setTimeout(() => {
          getDate();
        }, 1000);
      } else {
        message.error('删除失败' + res.message);
      }
    } catch (e: any) {
      message.error('删除失败' + e.message);
    }
    setLoading(false);
  };
  /**
   * 钩子函数，首次加载页面的时候运行
   */

  useEffect(() => {
    getDate();
  }, [searchParams]);

  return (
    <ProTable<GithubIssueItem>
      columns={columns}
      search={false}
      loading={loading}
      cardBordered
      dataSource={usertList}
      editable={{
        type: 'multiple',
        onSave: async (rowKey, data, row) => {
          await editUser(data.id, data.userRole);
        },
      }}
      rowKey="id"
      options={{
        setting: {
          listsHeight: 400,
        },
      }}
      pagination={{
        onChange: (page, pageSize) => {
          setSearchParams({
            ...searchParams,
            current: page,
            pageSize: pageSize,
          });
        },
        current: searchParams.current,
        pageSize: searchParams.pageSize,
        total: total,
      }}
      dateFormatter="string"
      headerTitle="用户列表"
    />
  );
};
export default UserList;
